package no.awerup.armory_miner;

import no.awerup.armory_miner.collectors.CharCollector;
import no.awerup.armory_miner.collectors.Collector;

import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.camel.component.ActiveMQComponent;
import org.apache.camel.CamelContext;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DataCollector 
{
	private CamelContext camelContext;

	public void setCamelContext(CamelContext camelContext) {
		this.camelContext = camelContext;
	}
	
	private void startEmbeddedBroker(){
		// Create embeded broker
		BrokerService broker = new BrokerService();
		
		try {
			broker.addConnector("tcp://localhost:61616");
			broker.start();
		} catch (Exception e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
	}
	
	private void startCamelContext(){
	
		// Create Camel context
		try {
	    	camelContext.addComponent("amq", ActiveMQComponent.activeMQComponent("vm://localhost?broker.persistent=false"));
	    	
	    	camelContext.addRoutes(new RouteBuilder() {
	    		Processor charProcessor = new CharCollector();
	    	    public void configure() {
	    	        from("amq:queue:test.queue").throttler(1).timePeriodMillis(10000).process(charProcessor);	    	        
	    	    }
	    	});
		    	
			camelContext.start();
			
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
	
	
				

	
    public static void main( String[] args )
    {
    	setEnvironmentVariables();
    	ApplicationContext springContext = new ClassPathXmlApplicationContext( new String[] {"collectorContext.xml"});
    	
    	// Start data collector
    	DataCollector dc = (DataCollector) springContext.getBean( "dataCollector" );
		dc.startEmbeddedBroker();
    	dc.startCamelContext();
    	
    	
    	// Test kode
    	Collector gColl = (Collector) springContext.getBean( "guildCollector" );
    	try {
			gColl.process(null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	    	
    }

	

	

	private static void setEnvironmentVariables() {
		System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
    	System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
    	System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "debug");
    	System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");
	}
}
